<?php

namespace support;

use Webman\Captcha\CaptchaBuilder;
use Webman\Captcha\PhraseBuilder;

class Captcha
{
    public static function generate()
    {
        // 验证码长度
        $length = 4;
        // 包含哪些字符
        $chars = '0123456789';
        $phraseBuilder  = new PhraseBuilder($length, $chars);
        $builder = new CaptchaBuilder(null, $phraseBuilder);

        // 生成验证码
        $builder->build();

        $key = self::generateStoreKey();

        Cache::set($key, strtolower($builder->getPhrase()));

        $body = 'data:image/jpeg;base64,' . base64_encode($builder->get());
        return ['key' => $key, 'captcha' => $body];
    }

    public static function check($captcha, $key)
    {
        $value = Cache::get($key);

        Cache::delete($key);

        print_r([$captcha, $value, $value == strtolower($captcha)]);

        if ($value && $value == strtolower($captcha)) {
            return true;
        }

        return false;
    }

    public static function generateStoreKey()
    {
        return 'captcha_' . md5(uniqid(mt_rand(), true));
    }
}